class WebSocketService {
  private connections: Map<string, WebSocket> = new Map();
  private reconnectAttempts: Map<string, number> = new Map();
  private maxReconnectAttempts = 3;

  connect(taskType: string, handlers: {
    onMessage: (data: any) => void;
    onError: (error: any) => void;
    onComplete?: () => void;
  }): WebSocket | null {
    // 获取认证token
    const token = localStorage.getItem('token');
    if (!token) {
      console.error(`WebSocket连接失败: 未找到认证token，请先登录`);
      handlers.onError(new Error('未认证'));
      return null;
    }

    // 构建WebSocket URL - 直接连接到后端
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsHost = 'localhost:8001'; // 直接连接到后端WebSocket服务
    const wsUrl = `${protocol}//${wsHost}/ws/download-progress/${taskType}/?token=${token}`;

    try {
      const ws = new WebSocket(wsUrl);
      
      ws.onopen = () => {
        console.log(`WebSocket connected for ${taskType}`);
        this.connections.set(taskType, ws);
        this.reconnectAttempts.set(taskType, 0);
      };

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          handlers.onMessage(data);
          
          if (data.status === 'completed' && handlers.onComplete) {
            handlers.onComplete();
          }
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error);
        }
      };

      ws.onclose = (event) => {
        console.log(`WebSocket closed for ${taskType}:`, event.code, event.reason);
        this.connections.delete(taskType);
        
        // 只有在非正常关闭时才尝试重连
        if (event.code !== 1000 && event.code !== 1001) {
          const attempts = this.reconnectAttempts.get(taskType) || 0;
          if (attempts < this.maxReconnectAttempts) {
            this.reconnectAttempts.set(taskType, attempts + 1);
            console.log(`Attempting to reconnect WebSocket for ${taskType} (attempt ${attempts + 1})`);
            setTimeout(() => {
              this.connect(taskType, handlers);
            }, 2000 * (attempts + 1)); // 指数退避
          } else {
            console.error(`Max reconnection attempts reached for ${taskType}`);
            handlers.onError(new Error('连接失败'));
          }
        }
      };

      ws.onerror = (error) => {
        console.error(`WebSocket error for ${taskType}:`, error);
        console.error(`WebSocket URL: ${wsUrl}`);
        console.error(`WebSocket readyState: ${ws.readyState}`);
        console.error(`Browser WebSocket support: ${typeof WebSocket !== 'undefined'}`);
        
        // 只在连接阶段报错时调用外部错误处理
        if (ws.readyState === WebSocket.CONNECTING) {
          handlers.onError(error);
        }
      };

      return ws;
    } catch (error) {
      console.error(`Failed to create WebSocket connection for ${taskType}:`, error);
      handlers.onError(error);
      return null;
    }
  }

  disconnect(taskType: string): void {
    const ws = this.connections.get(taskType);
    if (ws) {
      ws.close();
      this.connections.delete(taskType);
      this.reconnectAttempts.delete(taskType);
    }
  }

  disconnectAll(): void {
    this.connections.forEach((ws, taskType) => {
      ws.close();
    });
    this.connections.clear();
    this.reconnectAttempts.clear();
  }

  isConnected(taskType: string): boolean {
    const ws = this.connections.get(taskType);
    return ws ? ws.readyState === WebSocket.OPEN : false;
  }
}

export const websocketService = new WebSocketService();
export default websocketService;